package demo;

public class Demo4 {
    public static void main(String[] args) throws InterruptedException {
        Object lockerA=new Object();
        Object lockerB=new Object();
        //按照同一顺序加锁，破坏循环等待
        Thread t1=new Thread(()->{
            synchronized (lockerA){
                //加sleep以保证对方线程能加上锁，否则不一定出现死锁
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (lockerB){
                    System.out.println("t1");
                }
            }

        });
        Thread t2=new Thread(()->{
            synchronized (lockerA) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                synchronized (lockerB) {
                    System.out.println("t2");
                }
            }
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
    }
}
